package modules.majiang.viewManager
{
	import com.netease.protobuf.UInt64;

	import flash.display.Bitmap;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;

	import communication.majiang.MajiangMsgEvent;

	import modules.GameEvent;
	import modules.ViewManager;
	import modules.majiang.MajiangEvent;
	import modules.majiang.data.TableDataModel;
	import modules.majiang.data.TablePlayerDataModel;
	import modules.majiang.data.TablesDataManager;
	import modules.manager.SoundManager;

	import protobuf.MSPKG_DISCARD_NTF;
	import protobuf.MSPKG_DIST_TILES_NTF;
	import protobuf.MSPKG_SHOW_TILES_NTF;
	import protobuf.MSPKG_TILES_NTF;

	import utils.BigCardFactory;
	import utils.TileTransform;

	/**
	 * @author xumin.xu 2013-1-21
	 */
	public class OwnCardsViewManager extends ViewManager
	{
		private var tableId:UInt64;

		private var ownCards:MovieClip;

		private var playerCardBitmaps:Array = [];

		/** 此次出牌的位置 */
		public var discardIndex:int;

		/**
		 * 当前弹起的牌
		 **/
		private var upCard:*;

		/**
		 * 胜利时牌的光效
		 **/
		private var winGlow:GlowFilter = new GlowFilter(0xffff00, 1, 20, 20, 2, 2);

		public function OwnCardsViewManager(tableId:UInt64, tableView:MovieClip)
		{
			super();
			this.tableId = tableId;

			this.mainUI = tableView;

			discardIndex = tableDataModel ? tableDataModel.handTilesNum : 7;

			ownCards = tableView.playerCard_1;
			ownCards.buttonMode = true;

			var j:int;
			for (j = 1; j <= 8; j++)
			{
				var card:* = ownCards["card_" + j];
				var cardBitmap:Bitmap = new Bitmap();
				cardBitmap.name = "cardBitmap";
				playerCardBitmaps[j] = cardBitmap;
				card.addChild(playerCardBitmaps[j]);
			}

			tableView.addEventListener(Event.ADDED_TO_STAGE, onAddToStage);
			tableView.addEventListener(Event.REMOVED_FROM_STAGE, removeFromStage);
		}

		/**
		 * 桌子数据
		 **/
		public function get tableDataModel():TableDataModel
		{
			return TablesDataManager.tableDataModeDic[tableId.toString()];
		}

		private function onAddToStage(event:Event):void
		{
			//更新麻将桌子界面中显示
			dispatcher.addEventListener(MajiangEvent.UPDATE_MAJIANG_TABLE_VIEW, onUpdateTableView);

			//第一轮的7张牌
			dispatcher.addEventListener(MSProto.MSID_DIST_TILES_NTF.toString(), onDistTilesNtf);

			//回应玩家自己出牌请求
			dispatcher.addEventListener(MSProto.MSID_DISCARD_ACK.toString(), function(event:MajiangMsgEvent):void
			{
				if (event.data != tableId.toString())
					return;
				updateViewData();
				discardIndex = tableDataModel.handTilesNum;
			});

			//玩家出牌
			dispatcher.addEventListener(MSProto.MSID_DISCARD_NTF.toString(), function(event:MajiangMsgEvent):void
			{
				var pkg:MSPKG_DISCARD_NTF = event.data;
				if (pkg.tableId.toString() != tableId.toString())
					return;
				updateViewData();
			});

			//比赛结束10后清空桌面
			dispatcher.addEventListener(MajiangEvent.CLEAR_TABLE_INFO, function(event:GameEvent):void
			{
				if (tableId.toString() != event.data)
					return;
				//更新桌子上的牌
				updateViewData();
			});

			//赢牌的时候show自己的牌
			dispatcher.addEventListener(MSProto.MSID_SHOW_TILES_NTF.toString(), function(event:GameEvent):void
			{
				var pkg:MSPKG_SHOW_TILES_NTF = event.data;
				if (pkg.tableId.toString() != tableId.toString())
					return;
				updateViewData();
			});

			//广播某玩家手牌
			dispatcher.addEventListener(MSProto.MSID_TILES_NTF.toString(), function(event:GameEvent):void
			{
				var pkg:MSPKG_TILES_NTF = event.data;
				if (pkg.tableId.toString() != tableId.toString())
					return;
				updateViewData();
			});

			//用户弃牌广播
			dispatcher.addEventListener(MSProto.MSID_FOLD_NTF.toString(), onFoldNtf);

			//发牌动画结束
			dispatcher.addEventListener(MajiangEvent.FETCH_EFFECT_FINISH, onFetchEffectFinish);

			ownCards.addEventListener(MouseEvent.MOUSE_OVER, onOwnCardOver);

			ownCards.addEventListener(MouseEvent.CLICK, onClickMahjongCard);

			dispatcher.addEventListener(MajiangEvent.GET_FETCH_INFO, onGetFetchInfo);

			dispatcher.addEventListener(MajiangEvent.GET_OWN_DISCARD_INDEX, onGetOwnDiscardIndex);

		}

		private function removeFromStage(event:Event):void
		{
			dispatcher.removeEventListener(MajiangEvent.UPDATE_MAJIANG_TABLE_VIEW, onUpdateTableView);

			dispatcher.removeEventListener(MSProto.MSID_DIST_TILES_NTF.toString(), onDistTilesNtf);

			dispatcher.removeEventListener(MajiangEvent.FETCH_EFFECT_FINISH, onFetchEffectFinish);
		}

		private function onUpdateTableView(event:MajiangEvent):void
		{
			if (tableId.toString() != event.data.tableId.toString())
				return;
			updateViewData();
		}

		private function onFetchEffectFinish(event:MajiangEvent):void
		{
			if (event.data.position == 1)
			{
				updateViewData();
			}
		}

		private function onDistTilesNtf(event:MajiangMsgEvent):void
		{
			var pkg:MSPKG_DIST_TILES_NTF = event.data;
			if (pkg.tableId.toString() != tableId.toString())
				return;

			if (event.data.tilesCount == tableDataModel.handTilesNum)
			{
				updateViewData();
			}
		}

		private function onFoldNtf(event:GameEvent):void
		{
			if (tableId.toString() != event.data)
				return;
			updateViewData();
		}

		/**
		 * 刷新数据
		 **/
		private function updateViewData():void
		{
			var position:int = 1;
			var chairId:int;
			var tiles:Array;
			var tablePlayerDataModel:TablePlayerDataModel;

			chairId = tableDataModel.getChairIdByPosition(position);
			if (tableDataModel.sitChairId > 0)
			{
				tiles = tableDataModel.tilesInHand;
				ownCards.mouseEnabled = tableDataModel.disableDiscard;
				ownCards.mouseChildren = tableDataModel.disableDiscard;
			}
			else
			{
				ownCards.mouseEnabled = false;
				ownCards.mouseChildren = false;
				tiles = tableDataModel.playerTiles[chairId];
			}
			ownCards.visible = (tiles != null && tiles.length > 0);

			for (var j:int = 1; j <= 8; j++)
			{
				var card:* = ownCards["card_" + j];
				card.visible = j <= tiles.length;
				var tile:Object = tiles[j - 1];

				if (tableDataModel.handTilesNum + 1 == j)
				{
					var preCard:* = ownCards["card_" + (j - 1)];
					card.x = preCard.x + preCard.width + 10;
				}

				var cardBitmap:Bitmap = playerCardBitmaps[j];
				if (tile)
				{
					cardBitmap.bitmapData = BigCardFactory.getNormalCardBitmapData(tile.type, tile.value);
					cardBitmap.visible = true;
				}
				else
				{
					cardBitmap.visible = false;
				}
			}

			updateShowState();
		}

		/**
		 * 更新显示状态
		 **/
		private function updateShowState():void
		{
			var isWin:Boolean = tableDataModel.isWin(tableDataModel.lookChairId);
			var isFold:Boolean = tableDataModel.isFold(tableDataModel.lookChairId);
			var isLose:Boolean = tableDataModel.isLose(tableDataModel.lookChairId);
			var isDraw:Boolean = tableDataModel.isDraw(tableDataModel.lookChairId);

			//如果是观察者，显示观察者牌
			var tiles:Array = tableDataModel.playerTiles[tableDataModel.lookChairId];
			if (isWin && tiles[0] != null)
			{
				ownCards.alpha = 1;
				ownCards.filters = [winGlow];
			}
			else if (isFold || isLose || isDraw)
			{
				ownCards.alpha = 0.7;
				ownCards.filters = [];
			}
			else
			{
				ownCards.alpha = 1;
				ownCards.filters = [];
			}
		}

		private function onOwnCardOver(event:MouseEvent):void
		{
			if (tableDataModel.sitChairId > 0 && tableDataModel.disableDiscard)
			{
				switch (event.target.name)
				{
					case "card_1":
					case "card_2":
					case "card_3":
					case "card_4":
					case "card_5":
					case "card_6":
					case "card_7":
					case "card_8":
						if (upCard != null)
						{
							upCard.y = 0;
						}
						event.target.y = -12;
						if (upCard != event.target)
						{
							upCard = event.target;
							SoundManager.instance.chooseTilePlay();
						}
						break;
				}
			}
		}

		/**
		 * 玩家点击麻将，表示出牌
		 **/
		private function onClickMahjongCard(event:MouseEvent):void
		{
			if (tableDataModel.sitChairId > 0 && tableDataModel.disableDiscard)
			{

				switch (event.target.name)
				{
					case "card_1":
					case "card_2":
					case "card_3":
					case "card_4":
					case "card_5":
					case "card_6":
					case "card_7":
					case "card_8":
						var cardIndex:int = int(event.target.name.split("_")[1]);
						var tile:Object = tableDataModel.tilesInHand[cardIndex - 1];
						var tileValue:uint = TileTransform.clienToServer(tile);
						var tableId:UInt64 = tableDataModel.tableDataFromLobby.tableID;

						//不允许出宝牌
						if (tileValue != 41)
						{
							dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_DISCARD_REQ.toString(), {tableId: tableId, tile: tileValue}));
							if (upCard != null)
							{
								upCard.y = 0;
								upCard = null;
							}
							discardIndex = cardIndex;
						}
						break;
				}
			}
		}

		private function onGetFetchInfo(event:MajiangEvent):void
		{
			if (event.data.position == 1)
			{
				event.data.fetchToCard = ownCards["card_" + event.data.cardIndex];
			}
		}

		private function onGetOwnDiscardIndex(event:MajiangEvent):void
		{
			event.data.discardIndex = discardIndex;
		}

	}
}
